package com.hspedu.newData.dmsxl.树.二叉树的遍历;

import com.hspedu.newData.dmsxl.ds.TreeNode;
import org.junit.Test;

import java.util.*;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-05-13 
 * @Version: 1.0
 */

public class LC103二叉树的锯齿形层序遍历 {

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {

        List<List<Integer>> ans = new LinkedList<List<Integer>>();
        if (root == null) {
            return ans;
        }

        Queue<TreeNode> nodeQueue = new ArrayDeque<TreeNode>();
        nodeQueue.offer(root);
        boolean isOrderLeft = true;

        while (!nodeQueue.isEmpty()) {
            Deque<Integer> levelList = new LinkedList<Integer>();
            int size = nodeQueue.size();
            for (int i = 0; i < size; ++i) {
                TreeNode curNode = nodeQueue.poll();
                if (isOrderLeft) {
                    levelList.offerLast(curNode.val);
                } else {
                    levelList.offerFirst(curNode.val);
                }
                if (curNode.left != null) {
                    nodeQueue.offer(curNode.left);
                }
                if (curNode.right != null) {
                    nodeQueue.offer(curNode.right);
                }
            }
            ans.add(new LinkedList<Integer>(levelList));
            isOrderLeft = !isOrderLeft;
        }

        return ans;
    }

    @Test
    public void test() {
        // 测试代码

        // 测试代码

        TreeNode t7 = new TreeNode(7);
        TreeNode t6 = new TreeNode(6);
        TreeNode t5 = new TreeNode(5);
        TreeNode t4 = new TreeNode(4);
        TreeNode t3 = new TreeNode(3,t6,t7);
        TreeNode t2 = new TreeNode(2,t4,t5);
        TreeNode t1 = new TreeNode(1,t2,t3);

        zigzagLevelOrder(t1);
        System.out.println("==========");
    }
}
